package game

import (
	"MyWuXiaGame/server/src/csvs"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type SkillInfo struct {
	SkillId 	int
	SkillLv		int
	SkillExp	int
}

type ModSkill struct {
	LearnedSkillInfo map[int]*SkillInfo

	player *Player
	path   string
}

func (self *ModSkill) HandleViewAllSkill() {
	fmt.Println("当前学会的武学：")
	for _, v := range self.LearnedSkillInfo {
		SkillConfig := csvs.ConfigSkillLevelMap[v.SkillId][v.SkillLv]
		if SkillConfig != nil {
			fmt.Println("武学id：", v.SkillId, "武学名字：", SkillConfig.SkillName,"武学等级：", v.SkillLv, "当前经验：", v.SkillExp)
		}
	}
}

func (self *ModSkill) HandleLearnSkill() {
	fmt.Println("这天你在村子后山打猎的时候意外发现了一个山洞，里面刻着不少壁画看起来像某些武学，突然间山洞开始崩塌，时间紧迫，你只来得及记住一门武学")
	fmt.Println("请选择想学习的武学id 1虾米拳法2太极拳3如来神掌4玉女剑法5九阴白骨爪 0返回")
	var skillid int
	fmt.Scan(&skillid)

	if skillid == 0 {
		return
	}

	if skillid == 6 {
		fmt.Println("该武学不可学习")
		return
	}

	SkillLevelMap := csvs.ConfigSkillLevelMap[skillid]
	if SkillLevelMap == nil {
		fmt.Println("该武学不可学习")
		return
	}

	SkillData := self.LearnedSkillInfo[skillid]
	if SkillData != nil {
		fmt.Println("已学过该武学")
		return
	}

	SkillData = new(SkillInfo)
	SkillData.SkillId = skillid
	SkillData.SkillLv = 1
	SkillData.SkillExp = 0

	self.LearnedSkillInfo[skillid] = SkillData

	fmt.Println("已学会该武学")
}

func (self *ModSkill) HandleTrainSkill() {
	for {
		fmt.Println("请选择想修炼的武学id")
		var skillid int
		fmt.Scan(&skillid)
		fmt.Println("请选择想修炼的天数，一天增加10exp 0返回")
		var days int
		fmt.Scan(&days)

		if days == 0 {
			return
		}

		SkillData := self.LearnedSkillInfo[skillid]
		if SkillData == nil {
			fmt.Println("您还未学会该武学")
			return
		}

		SkillData.SkillExp += days*10
		for {
			config := csvs.ConfigSkillLevelMap[SkillData.SkillId][SkillData.SkillLv]
			if config == nil {
				break
			}
			if config.SkillExp == 0 {
				break
			}

			if SkillData.SkillExp >= config.SkillExp {
				nextconfig := csvs.ConfigSkillLevelMap[SkillData.SkillId][SkillData.SkillLv + 1]
				if nextconfig != nil {
					SkillData.SkillLv += 1
					SkillData.SkillExp -= config.SkillExp
				} else {
					SkillData.SkillExp = config.SkillExp
					fmt.Println("该武学已修炼至极限")
					break
				}
			} else {
				break
			}
		}
	}
}

func (self *ModSkill) SaveData() {
	content, err := json.Marshal(self)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(self.path, content, os.ModePerm)
	if err != nil {
		return
	}
}

func (self *ModSkill) LoadData(player *Player) {

	self.player=player
	self.path=self.player.localPath+"/Skill.json"

	configFile, err := ioutil.ReadFile(self.path)
	if err != nil {
		self.InitData()
		return
	}
	err = json.Unmarshal(configFile, &self)
	if err != nil {
		self.InitData()
		return
	}

	if self.LearnedSkillInfo==nil{
		self.LearnedSkillInfo=make(map[int]*SkillInfo,0)
	}

	return
}

func (self *ModSkill) InitData() {
	if self.LearnedSkillInfo==nil{
		self.LearnedSkillInfo=make(map[int]*SkillInfo,0)
	}
}